﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Hydra.Shell.Interfaces;
using Utils;
using Hydra.Shell.Enumerations;
using System.Diagnostics;

namespace Hydra.Shell.Implementations
{
    public class HydraServiceWrapper : HydraObjectWrapper
    {
        public event EventHandler Disposed;
        private WeakReference<IUnknown> weakReference;
        private IUnknown strongReference;
        private Guid serviceGuid;
        public static EventHandler ObjectDisposed { get; set; }
        public bool IsDisposed { get; private set; }

        static HydraServiceWrapper()
        {
            _HydraServiceBase.Disposed += (sender, e) =>
            {
                if (ObjectDisposed != null)
                {
                    ObjectDisposed(sender, e);
                }
            };

        }

        public HydraServiceWrapper(Guid serviceGuid, IUnknown service)
        {
            this.serviceGuid = serviceGuid;

            HydraServiceWrapper.ObjectDisposed += (sender, e) =>
            {
                if (sender == weakReference.Object)
                {
                    this.IsDisposed = true;
                }
            };

            var lifetimeType = GetLifetimeType(service);

            switch (lifetimeType)
            {
                case ServiceLifetimeType.NormalGarbageCollected:
                    weakReference = new WeakReference<IUnknown>(service);
                    break;
                case ServiceLifetimeType.ShellInstance:
                    strongReference = service;
                    break;
                case ServiceLifetimeType.PerThread:
                case ServiceLifetimeType.ExternallyControlled:

                    Debugger.Break(); // TODO
                    break;
            }
        }

        public IUnknown Service
        {
            get
            {
                if (weakReference != null)
                {
                    if (this.IsDisposed)
                    {
                        throw new ObjectDisposedException(string.Format("Service {{{0}}}}", serviceGuid));
                    }

                    return weakReference.Object;
                }
                else
                {
                    return strongReference;
                }
            }
        }

        public Guid ServiceGuid
        {
            get
            {
                if (this.IsDisposed)
                {
                    throw new ObjectDisposedException(string.Format("Service {{{0}}}}", serviceGuid));
                }

                return serviceGuid;
            }
        }
    }
}
